package com.yc.qunxing.web;


import com.yc.qunxing.entity.DriverLocations;
import com.yc.qunxing.result.Result;
import com.yc.qunxing.service.IDriverLocationsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 鹏哥
 * @since 2024-05-23
 */
@RestController
@RequestMapping("/driver-locations")
public class DriverLocationController {

    @Autowired
    private IDriverLocationsService iDriverLocationsService;

    @GetMapping("/locationById")
    public Result<String> LocationById(@RequestParam Integer driverId){
        DriverLocations byId = iDriverLocationsService.getById(driverId);
        if (byId != null && byId.getLocation() != null) {
            return Result.success(byId.getLocation());
        } else {
            return Result.error("请输入您的当前位置");
        }
    }

    @PostMapping("/addLocation")
    public Result<String> addLocation(@RequestBody DriverLocations driverLocations){
        boolean save = iDriverLocationsService.saveOrUpdate(driverLocations);
        if (save) {
            return Result.success(driverLocations.getLocation());
        } else {
            return Result.error("位置保存失败");
        }
    }

    @PutMapping("/updateLocationById")
    public Result<String> UpdateLocationById(@RequestBody DriverLocations driverLocations){
        String time = driverLocations.getTime();
        // 定义字符串的格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 解析字符串为 LocalDateTime
        LocalDateTime localDateTime = LocalDateTime.parse(time, formatter);
        driverLocations.setLastUpdated(localDateTime);
        iDriverLocationsService.updateById(driverLocations);
        return Result.success("修改位置成功");
    }
}
